package testconfig

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TestDingTalkLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewTestDingTalkLogic 钉钉测试
func NewTestDingTalkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TestDingTalkLogic {
	return &TestDingTalkLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TestDingTalkLogic) TestDingTalk(req *types.TestDingTalkRequest) (*types.TestResponse, error) {
	// 检查是否提供了钉钉配置
	if len(req.Config) == 0 {
		return &types.TestResponse{
			Success: 500,
			Message: "未提供钉钉配置",
		}, nil
	}

	// 取第一个配置
	config := req.Config[0]

	payload := map[string]interface{}{
		"msgtype": "text",
		"text": map[string]string{
			"content": config.Message,
		},
	}
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "json序列化失败",
		}, err
	}

	// 发送HTTP请求到钉钉
	response, err := http.Post(config.WebhookURL, "application/json", bytes.NewBuffer(payloadBytes))
	if err != nil {
		return &types.TestResponse{
			Success: 500,
			Message: "发送消息到钉钉失败",
		}, err
	}
	defer response.Body.Close()

	// 检查响应状态
	if response.StatusCode != http.StatusOK {
		return &types.TestResponse{
			Success: 500,
			Message: "钉钉响应非200状态",
		}, nil
	}

	return &types.TestResponse{
		Success: 200,
		Message: "消息成功发送到钉钉",
	}, nil
}
